<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security" xmlns:auth=""
>
<auth:data uri="/system/ws/list.json"/>

<head>
    <th:block th:include="common/head::noXadmin('WebSocket')"/>
</head>
<body>
<div style="margin-top:20px;margin-left: 20px;" class="layui-container">
    <div class="layui-row layui-col-space20 ">
        <div class="layui-col-xs3">
            <button type="button" class="layui-btn" id="reloadBtn">刷新列表</button>
            <table class="layui-table" lay-skin="line" lay-size="sm">
                <colgroup>
                    <col width="20%">
                    <col width="80%">
                </colgroup>
                <tbody id="userList">

                </tbody>
            </table>
        </div>
        <div class="layui-col-xs8">
            <form class="layui-form" action="">
                <div class="layui-form-item layui-hide">
                    <label class="layui-form-label">接收人ID</label>
                    <div class="layui-input-block">
                        <input type="number" name="toUserId" lay-verify="" autocomplete="off"
                               class="layui-input" id="toUserId">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">消息类型</label>
                    <div class="layui-input-block">
                        <select name="type" class="">
                            <option value="TXT">文本</option>
                            <option value="BYTE">二进制</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">内容</label>
                    <div class="layui-input-block">
                        <textarea placeholder="请输入内容" name="textData" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            <div style="margin-left: 40px;">
                <ul class="layui-timeline" id="msgBox">
                </ul>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="msgTmpl">
    <li class="layui-timeline-item">
        <i class="layui-icon layui-icon-circle layui-timeline-axis"></i>
        <div class="layui-timeline-content layui-text">
            <div class="layui-timeline-title">{{d.time}} ， {{d.msg}}</div>
        </div>
    </li>
</script>

<script>
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }
    layui.use(['jquery', 'form', 'laytpl'], function () {
        var $ = layui.jquery
            , form = layui.form
            , laytpl = layui.laytpl
            , layer = layui.layer
        ;
        if (!authInfo.isLogin) {
            return;
        }

        function reloadUsers() {
            let box = $("#userList");
            $.get("/system/ws/list.json", function (resp) {
                box.html('');
                if (resp.code != 0 || resp.data.length == 0) {
                    box.html('<tr><td colspan="2">无用户在线</td></tr>');
                    return;
                }
                for (let i = 0; i < resp.data.length; i++) {
                    let u = resp.data[i];
                    box.append(
                        [
                            '<tr uid=', u.user_id, '>'
                            , '<td><img src="', u.avatar, '" class="layui-circle " style="width:40px"/></td>'
                            , '<td>', u.user_id, '<br/>', u.name, '</td>'
                            , '</tr>'
                        ].join('')
                    )
                }
                $("#userList tr").on('click', function (event) {
                    $("#toUserId").val($(this).attr('uid'));
                })
            })
        }

        $("#reloadBtn").on('click', reloadUsers);

        //监听提交
        form.on('submit(demo1)', function (data) {
            send(JSON.stringify(data.field));
            return false;
        });

        function appendMsg(data) {
            data.time = new Date().format('yyyy-MM-dd hh:mm:ss ');
            laytpl($("#msgTmpl").html()).render(data, function (result) {
                $("#msgBox").prepend(result)
            });
        }

        let wsUrl = "ws://" + app.host + "/wss/" + authInfo.uid;
        let ws = new WebSocket(wsUrl);
        ws.onopen = function () {
            let data = {"msg": "开启连接"};
            appendMsg(data);
            console.log("ws opened ")
            reloadUsers();
        }
        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            let data = {"msg": "接收消息 " + received_msg};
            appendMsg(data);
        };
        ws.onclose = function () {
            let data = {"msg": "连接已关闭"};
            appendMsg(data);
            reloadUsers();
        };

        function send(data) {
            let d = {"msg": "发送消息，" + data};
            appendMsg(d);
            ws.send(data);
        }
    });
</script>

</body>

</html>
